<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Constant\ErrorConstant;
use App\MultiTrait\ResponseTrait;
use App\MultiTrait\PassportTrait;
use App\Admin;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers, PassportTrait, ResponseTrait;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'username' => ['required', 'string', 'max:255'],
//            'email' => ['required', 'string', 'email', 'max:255'],
            'phone' =>  ['regex:/^1[345789][0-9]{9}$/'],
            'password' => ['required', 'string', 'min:8'],  //, 'confirmed'
        ], [
            'username.required' =>  '用户名不能为空',
            'username.string'   =>  '用户名必须为字符',
            'username.max'      =>  '用户名过长',
            'phone.regex'       =>  '手机号码格式不正确',
            'password.required' =>  '密码不能为空',
            'password.string'   =>  '密码必须为字符',
            'password.min'      =>  '密码长度过短',
        ]);
    }

    /**
     * 后台登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function login(Request $request)
    {
        /*$json_content   =   $request->getContent();
        if (!empty($json_content)) {
            $json_content   =   json_decode($json_content, true);
        }*/
        $request->merge($request->json()->all() ?? []);

        $request_data=  $request->all();
        $validator  =   $this->validator($request_data);

        if ($validator->fails()) {
            return $this->errorResponse(ErrorConstant::PARAM_ERROR, $validator->errors()->first());
        }

        /**
         * 检测用户
         */
        $username   =   $request_data['username'];
        $login_result   =   Admin::where(['username' => $username])->orWhere(['phone' => $username])->select('username', 'phone', 'email', 'password')->first();
        if (empty($login_result)) {
            return $this->errorResponse(ErrorConstant::USERNAME_ERROR);
        }

        /**
         * 检测密码
         */
        $password   =   $request_data['password'];
        if (!Hash::check($password, $login_result->password)) {
            return $this->errorResponse(ErrorConstant::PASSWORD_ERROR);
        }

        return $this->successResponse($this->authenticate('admin', [
            'grant_type'    =>  'password',
            'client_id'     =>  '2',
            'client_secret' =>  'hFautrzq86i0jIPaq8FLonaKLmmfiMcnx0KgJG5K',
            'username'      =>  $login_result->email,
            'password'      =>  $password,
            'scope'         =>  '',
            'guard_provider'=>  'admins'
        ]));
    }

    protected function guard()
    {
        return Auth::guard('admin');
    }
}
